package com.wxw.BaseLibrary.http.soap;


import com.wxw.BaseLibrary.http.soap.SoapListener;
import com.wxw.BaseLibrary.http.soap.SoapResponse;

/**
 * Created by user on 2016/5/9.
 */
public class SoapThreadPoster implements Runnable {
    public static final int COMMAND_START = 0;
    public static final int COMMAND_RESPONSE = 1;
    public static final int COMMAND_FINISH = 2;

    private final int what;
    private final SoapListener listener;

    private int command;
    private Response response;

    public SoapThreadPoster(int what, SoapListener listener) {
        this.what = what;
        this.listener = listener;
    }

    public void onStart() {
        this.command = COMMAND_START;
    }

    public void onResponse(Response response) {
        this.command = COMMAND_RESPONSE;
        this.response = response;
    }

    public void onFinished() {
        this.command = COMMAND_FINISH;
    }

    @Override
    public void run() {
        if (listener != null) {
            if (command == COMMAND_START) {
                listener.onStart(what);
            } else if (command == COMMAND_FINISH) {
                listener.onFinish(what);
            } else if (command == COMMAND_RESPONSE) {
                if (response == null) {
                    listener.onFailed(what, null, new Exception("Unknown abnormal."), 0, 0);
                } else {
                    if (response.isSucceed()) {
                        listener.onSucceed(what, response);
                    } else {
                        listener.onFailed(what, response.url(), response.getException(), response.getResponseCode(), response.getNetworkMillis());
                    }
                }
            }
        }
    }
}
